package com.newtouch.xcd.admin.utils.sequence;

import com.newtouch.xcd.admin.config.SequenceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalTime;

@Component
public class SequenceServiceImpl implements SequenceService {


    @Autowired
    private SequenceConfig sequenceConfig;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String dailyNext(String type) {
        SequenceConfig.Sequence sequence = sequenceConfig.getList()
                .stream()
                .filter(item -> item.getType().equalsIgnoreCase(type))
                .findAny()
                .orElseThrow(() -> new RuntimeException("未找到序列{" + type + "}的配置"));

        String redisKey = sequence.getCacheKey();
        //需要确保 set和expire在一个事务中
        if(!redisTemplate.hasKey(redisKey)) {
            redisTemplate.execute((RedisConnection connection) -> {
                Long ttl = Duration.between(LocalTime.now(),LocalTime.MAX).getSeconds();
                return connection.set(redisKey.getBytes(), "0".getBytes(), Expiration.seconds(ttl), RedisStringCommands.SetOption.SET_IF_ABSENT);
            });
        }

        //自增1
        Long value = redisTemplate.opsForValue().increment(redisKey, 1);
        return sequence.next(value);
    }

}
